package com.zzxx.userManagement.web;

import com.zzxx.userManagement.domain.User;
import com.zzxx.userManagement.service.UserService;
import com.zzxx.userManagement.service.impl.UserServiceImpl;
import com.zzxx.userManagement.utils.IdOrPwdException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/LoginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = request.getParameter("user");
        String password = request.getParameter("password");
        try {
            User loginUser = userService.login(user, password);
            request.getSession().setAttribute("user", loginUser);
            response.sendRedirect(request.getContextPath());
        } catch (IdOrPwdException e) {
            request.setAttribute("msg", e.getMessage());
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
